package com.blb.servlet;

import com.blb.service.ICommentService;
import com.blb.service.ITopicService;
import com.blb.service.impl.CommentServiceImpl;
import com.blb.pojo.Comment;
import com.blb.pojo.User;
import com.blb.utils.SpringUtils;
import com.blb.utils.UUIDUtils;
import com.blb.service.IUserService;
import com.blb.service.impl.UserServiceImpl;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;


@WebServlet("/comments/*")
public class CommentServlet extends BaseServlet {

    private ICommentService commentService = SpringUtils.getBean(ICommentService.class);
    private IUserService userService = SpringUtils.getBean(IUserService.class);

    /**
     * 添加评论
     *
     * @param req
     * @param resp
     */
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //jsp列表还未传值
        String topicId = req.getParameter("topicId");
        String image = req.getParameter("image");
        String message = req.getParameter("message");

        User user = (User) req.getSession().getAttribute("user");
        Comment comment = new Comment(UUIDUtils.getId(), topicId, message, image, user.getId());

        try {
            commentService.add(comment);
            resp.getWriter().write("ok");
        } catch (SQLException | IOException e) {
            e.printStackTrace();
            resp.getWriter().write("保存失败：" + e.getMessage());
        }
    }

    /**
     * 删除
     *
     * @param req
     * @param resp
     */
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String id = req.getParameter("id");

        try {
            commentService.delete(id);
            resp.getWriter().write("ok");
        } catch (SQLException e) {
            e.printStackTrace();
            resp.getWriter().write("删除失败：" + e.getMessage());
        }
    }

    /**
     * 评论区列表
     *
     * @param req
     * @param resp
     */
    public void list(HttpServletRequest req, HttpServletResponse resp) {

        try {
            User user = (User) req.getSession().getAttribute("user");
            req.setAttribute("user", user);
            List<Comment> commentList = commentService.list();
            req.setAttribute("commentList", commentList);
            List<User> userList = userService.list();
            req.setAttribute("userList", userList);
            req.getRequestDispatcher("/moments.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("msg", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}



